﻿using Blog.Core.EFcore;
using Blog.Core.IRepositories;
using Microsoft.EntityFrameworkCore;

namespace Blog.Core.Repositories
{
    /// <summary>
    /// 底层泛型仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Repository<T>: IRepository<T> where T : class,new()
    {
        /// <summary>
        /// 依赖注入
        /// </summary>
        private readonly DbContext _db;
        public Repository(DbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task Add(T entity)
        {
           await  _db.Set<T>().AddAsync(entity);
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task Delete(int id)
        {
            var list = _db.Set<T>().Find(id);
            if (list!=null)
            {
                _db.Set<T>().Remove(list);
            }
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAll()
        {
            return await _db.Set<T>().ToListAsync();
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 查询单条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> GetById(int id)
        {
            return await _db.Set<T>().FindAsync(id);
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task Update(T entity)
        {
             _db.Set<T>().Update(entity);
            //throw new NotImplementedException();
        }
    }
}